package com.ferris.redbook.service.strategy;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

@Component
public class LocalStorageStrategy implements FileStorageStrategy {

    @Value("${app.upload.base-path:/tmp/uploads}")
    private String basePath;

    @Value("${app.upload.access-url-base:/uploads}")
    private String accessUrlBase;

    @Override
    public String upload(MultipartFile file, String key, Map<String, String> metadata) {
        try {
            Path targetLocation = Paths.get(basePath, key);
            Files.createDirectories(targetLocation.getParent());
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 保存元数据到单独文件(可选)
            if (metadata != null && !metadata.isEmpty()) {
                saveMetadata(key, metadata);
            }

            return getUrl(key);
        } catch (IOException ex) {
            throw new RuntimeException("文件上传失败: " + ex.getMessage(), ex);
        }
    }

    @Override
    public String upload(InputStream inputStream, String key, String contentType, Map<String, String> metadata) {
        try {
            Path targetLocation = Paths.get(basePath, key);
            Files.createDirectories(targetLocation.getParent());
            Files.copy(inputStream, targetLocation, StandardCopyOption.REPLACE_EXISTING);

            if (metadata != null && !metadata.isEmpty()) {
                saveMetadata(key, metadata);
            }

            return getUrl(key);
        } catch (IOException ex) {
            throw new RuntimeException("文件上传失败: " + ex.getMessage(), ex);
        }
    }

    @Override
    public String getUrl(String key) {
        return accessUrlBase + "/" + key;
    }

    @Override
    public boolean delete(String key) {
        try {
            Path filePath = Paths.get(basePath, key);
            return Files.deleteIfExists(filePath);
        } catch (IOException ex) {
            throw new RuntimeException("文件删除失败: " + ex.getMessage(), ex);
        }
    }

    @Override
    public Map<String, String> getMetadata(String key) {
        try {
            Path metaPath = Paths.get(basePath, key + ".meta");
            if (Files.exists(metaPath)) {
                // 读取并解析元数据文件
                String content = new String(Files.readAllBytes(metaPath));
                Map<String, String> metadata = new HashMap<>();
                // 简化的元数据解析逻辑
                for (String line : content.split("\n")) {
                    String[] parts = line.split("=", 2);
                    if (parts.length == 2) {
                        metadata.put(parts[0], parts[1]);
                    }
                }
                return metadata;
            }
            return new HashMap<>();
        } catch (IOException ex) {
            throw new RuntimeException("获取元数据失败: " + ex.getMessage(), ex);
        }
    }

    @Override
    public boolean exists(String key) {
        return Files.exists(Paths.get(basePath, key));
    }

    private void saveMetadata(String key, Map<String, String> metadata) throws IOException {
        Path metaPath = Paths.get(basePath, key + ".meta");
        StringBuilder content = new StringBuilder();
        for (Map.Entry<String, String> entry : metadata.entrySet()) {
            content.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
        }
        Files.write(metaPath, content.toString().getBytes());
    }
}